package com.rub.android.base

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import com.rub.android.utils.BackPressedCall
import com.rub.android.utils.logI
import org.jetbrains.anko.startActivity

/**
 * 基础AppCompatActivity类
 */
abstract class BaseActivity : AppCompatActivity() {

    companion object {
        private val TAG: String = this.javaClass.simpleName
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(getLayoutId())
        logI(TAG, "start onCreate")
        initView()
        initListener()
    }

    /**
     * 获取getLayoutId
     * 在kotlin里，父类的方法要在子类override，必须要open关键字.
     */
    abstract fun getLayoutId(): Int
    open fun initView() {}
    open fun initListener() {}

    /**
     *onBackPressed
     */
    override fun onBackPressed() {
        supportFragmentManager.fragments.forEach {
            it?.let {
                if ((it as? BackPressedCall)?.onBackPressed() == true) {
                    return
                }
            }
        }
        super.onBackPressed()
    }

    /**
     *开启actiactivity并且finish当前界面
     */
    inline fun <reified T : BaseActivity> startActivityAndFinish() {
        startActivity<T>()
        finish()
    }


    /**
     * 监听事件跳转页面.
     */
    fun setOnClickListener(btn: Button, context: Context, cls: Class<*>) {
        btn.setOnClickListener {
            //监听按钮，如果点击，就跳转
            var intent = Intent()
            intent.setClass(context, cls)
            startActivity(intent)
        }
    }
}